require("Scripts/Common/Class")
require("Scripts/Common/Utility")

LoopList = Class()

function LoopList:Ctor()
	self._count = 0
	self._current_index = 1
	self._update_list = {}
end

function LoopList:AddUpdater(updater)
	if updater == nil then return end
	self._count = self._count + 1
	table.insert(self._update_list, updater)
end

function LoopList:RemoveUpdater(updater)
	if updater == nil or self._count == 0 then return end
	for k, v in ipair(self._update_list) do
		if v == updater then
			if self._current_index > k then self._current_index = self._current_index - 1 end
			table.remove(self._update_list, k)
			self._count = self._count - 1
			break
		end
	end
end

function LoopList:Reset()
	self._current_index = 1
	for k, v in pair(self._update_list) do
		v:Reset()
	end
end

function LoopList:SetTime(time)
	for k, v in ipair(self._update_list) do
		time = v:SetTime(time)
		if time == 0 then
			self._current_index = k
			return 0
		end
	end
	self._current_index = self._count + 1
	return time
end

function LoopList:IsCompleted()
	return self._current_index > self._count
end

function LoopList:Update(frame_time)
	if self._current_index > self._count then return end
	local updater = self._update_list[self._current_index]
	updater:Update(frame_time)
	if updater:IsCompleted() then
		self._current_index = self._current_index + 1
	end
end
